package hoan.mvc.controller;

import hoan.mvc.form.LoginForm;
import hoan.mvc.validator.LoginFormValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Horizon
 * 
 */
@Controller
@RequestMapping(value="/check")
public class LoginController {

	/**
	 * 
	 */
	@Autowired
	private LoginFormValidator loginFormValidator;
	
	/**
	 * 
	 */
	@Autowired
	private LoginForm loginForm;
	
	/**
	 * 
	 * @param binder
	 */
	@InitBinder(value="loginForm")
	public void initBinder(WebDataBinder binder) {

		binder.setValidator(loginFormValidator);
	}

	/**
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/index")
	public String initPage(ModelMap map){
		
		map.addAttribute("loginForm", loginForm);
		
		return "login";
	}
	
	/**
	 * 	
	 * @param loginForm
	 * @param map
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/login")
	public String normalSessionLogin(HttpSession session, @Valid LoginForm loginForm,
			BindingResult result, ModelMap map) {
		
		if (result.hasErrors()) {
			return "login";
		}
		
		session.setAttribute("loginForm", loginForm);
		map.addAttribute("loginForm", loginForm);

		return "login";
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request, ModelMap  map){
		
		request.getSession().invalidate();
		map.addAttribute("loginForm", new LoginForm());
		
		return "login";
	}
}
